package com.luomu.base.control.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson.JSON;
import com.luomu.base.api.bo.R;
import com.luomu.base.api.bo.SocialLoginBody;
import com.luomu.base.api.bo.UserLoginReqBO;
import com.luomu.base.api.bo.UserLoginRspBO;
import com.luomu.base.api.service.SysLoginService;
import com.luomu.base.control.config.properties.SocialLoginConfigProperties;
import com.luomu.base.control.config.properties.SocialProperties;
import com.luomu.base.control.utils.SocialUtils;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import me.zhyd.oauth.cache.AuthStateCache;

import java.io.IOException;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/oauth")
public class TokenController {

    private final SocialProperties socialProperties;

    @Autowired
    private  AuthStateCache authStateCache;

    @Autowired
    private SysLoginService socialRegister;

    /**
     * 第三方登录请求
     *
     * @param source 登录来源
     * @return 结果
     */
    @RequestMapping("/render/{source}")
    @ResponseBody
    public R<String> renderAuth(@PathVariable("source") String source, HttpServletResponse response) throws IOException {
        SocialLoginConfigProperties obj = socialProperties.getType().get(source);
        if (Objects.isNull(obj)) {
            return R.ok();
        }
        AuthRequest authRequest = SocialUtils.getAuthRequest(source, socialProperties);
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info(authorizeUrl);
//        response.sendRedirect(authorizeUrl);
        return R.ok(authorizeUrl);
    }

    /**
     * 第三方登录回调业务处理 绑定授权
     *
     * @param loginBody 请求体
     * @return 结果
     */
    @RequestMapping("/callback/{source}")
    public R<Void> socialCallback(@RequestBody SocialLoginBody loginBody) {
        log.info("====authStateCache========{}", JSON.toJSONString(authStateCache.containsKey(loginBody.getSocialState())));

        // 获取第三方登录信息
        AuthResponse<AuthUser> response = SocialUtils.loginAuth(
                loginBody.getSource(), loginBody.getSocialCode(),
                loginBody.getSocialState(), socialProperties);
        log.info("====response========{}", JSON.toJSONString(response));
        AuthUser authUserData = response.getData();
        // 判断授权响应是否成功
        if (!response.ok()) {
            return R.fail(response.getMsg());
        }

        // 登录
        Long openId = socialRegister.socialRegister(authUserData);
        UserLoginReqBO reqBO = new UserLoginReqBO();
        reqBO.setOpenId(openId);
        this.login(reqBO);

        return R.ok();
    }

    @RequestMapping("/login")
    public R<UserLoginRspBO> login(@RequestBody UserLoginReqBO reqBO) {
        if(!StpUtil.isLogin()){
            StpUtil.login(reqBO.getOpenId());
        }
        return R.ok();
    }

    @RequestMapping("/logout")
    public R<UserLoginRspBO> logout(@RequestBody UserLoginReqBO reqBO) {
        if(StpUtil.isLogin()){
            StpUtil.logout();
        }
        return R.ok();
    }

//    /**
//     * 取消授权
//     *
//     * @param socialId socialId
//     */
//    @DeleteMapping(value = "/unlock/{socialId}")
//    public R<Void> unlockSocial(@PathVariable Long socialId) {
//        Boolean rows = remoteSocialService.deleteWithValidById(socialId);
//        return rows ? R.ok() : R.fail("取消授权失败");
//    }

//
//    @RequestMapping("/revoke/{source}/{uuid}")
//    @ResponseBody
//    public R revokeAuth(@PathVariable("source") String source, @PathVariable("uuid") String uuid) throws IOException {
//        AuthRequest authRequest = SocialUtils.getAuthRequest(source.toLowerCase(), socialProperties);
//
//        AuthUser user = userService.getByUuid(uuid);
//        if (null == user) {
//            return Response.error("用户不存在");
//        }
//        AuthResponse<AuthToken> response = null;
//        try {
//            response = authRequest.revoke(user.getToken());
//            if (response.ok()) {
//                userService.remove(user.getUuid());
//                return Response.success("用户 [" + user.getUsername() + "] 的 授权状态 已收回！");
//            }
//            return Response.error("用户 [" + user.getUsername() + "] 的 授权状态 收回失败！" + response.getMsg());
//        } catch (AuthException e) {
//            return Response.error(e.getErrorMsg());
//        }
//    }
//
//    @RequestMapping("/refresh/{source}/{uuid}")
//    @ResponseBody
//    public Object refreshAuth(@PathVariable("source") String source, @PathVariable("uuid") String uuid) {
//        AuthRequest authRequest = SocialUtils.getAuthRequest(source.toLowerCase(), socialProperties);
//
//        AuthUser user = userService.getByUuid(uuid);
//        if (null == user) {
//            return Response.error("用户不存在");
//        }
//        AuthResponse<AuthToken> response = null;
//        try {
//            response = authRequest.refresh(user.getToken());
//            if (response.ok()) {
//                user.setToken(response.getData());
//                userService.save(user);
//                return Response.success("用户 [" + user.getUsername() + "] 的 access token 已刷新！新的 accessToken: " + response.getData().getAccessToken());
//            }
//            return Response.error("用户 [" + user.getUsername() + "] 的 access token 刷新失败！" + response.getMsg());
//        } catch (AuthException e) {
//            return Response.error(e.getErrorMsg());
//        }
//    }
}
